package com.liushuai.eas.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.liushuai.eas.common.ExcelUtil;
import com.liushuai.eas.common.MD5Util;
import com.liushuai.eas.common.OriginPsw;
import com.liushuai.eas.common.Result;
import com.liushuai.eas.pojo.*;
import com.liushuai.eas.service.TeacherImp;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController
@RequestMapping("/teacher")
public class TeacherController {

    @Resource
    private TeacherImp teacherImp;

    @PostMapping
    public Result<Teacher> add(@RequestBody Teacher teacher){
        //初始化密码
        teacher.setPassword(MD5Util.md5(OriginPsw.getOriginPassword()));
        if (teacherImp.insert(teacher)!=1)
            return Result.fail();
        return Result.success(teacher);
    }

    @PutMapping
    public Result<Teacher> update(@RequestBody Teacher teacher){
        teacher.setPassword(MD5Util.md5(teacher.getPassword()));
        if (teacherImp.updateById(teacher)!=1)
            return Result.fail(teacher);
        return Result.success(teacher);
    }

    @GetMapping
    public Result<?> findPage(@RequestParam(defaultValue = "1") Integer pageNum,
                              @RequestParam(defaultValue = "10") Integer pageSize,
                              @RequestParam(defaultValue = "") String search){
        Page<Teacher> teacherPage = teacherImp.selectPage(new Page<Teacher>(pageNum, pageSize), Wrappers.<Teacher>lambdaQuery().like(Teacher::getName, search));
        return Result.success("数据加载成功",teacherPage);
    }

    @DeleteMapping
    public Result<Teacher> delete(@RequestBody Teacher teacher){
        if (teacherImp.deleteById(teacher)!=1)
            return Result.fail(teacher);
        return Result.success(teacher);
    }

    @PostMapping("/login")
    public Result<?> login(@RequestBody Teacher teacher){
        String name = teacher.getName().trim();
        String password = teacher.getPassword().trim();
        teacher.setPassword(MD5Util.md5(password));
        Teacher tea = teacherImp.selectOne(Wrappers.<Teacher>lambdaQuery().eq(Teacher::getName, name));
        if (tea==null){
            return Result.fail("用户名或密码错误");
        }
        HashMap<Object, Object> map = new HashMap<>();
        map.put("user",tea);
        return Result.success("登录成功，您好！"+tea.getName()+"老师",map);
    }

    @GetMapping("/teacherCount")
    public Result<?> teacherCount(){
        int total = 0;
        HashMap<String,Object> map = new HashMap<String,Object>();
        total = teacherImp.queryTotal();
        map.put("id",1);
        map.put("name","教师人数");
        map.put("icon","el-icon-s-custom");
        map.put("total",total);
        return Result.success("数据加载成功",map);
    }

    @GetMapping("/exportData")
    public void exportData(@RequestParam String search,
                           @RequestParam Boolean isTemplate,
                           HttpServletResponse response) {
        ExcelUtil excelUtil = new ExcelUtil();
        List<Teacher> list;
        QueryWrapper<Teacher> queryWrapper = new QueryWrapper<>();
        if (!search.isEmpty()){
            queryWrapper.like("name",search);
        }
        //需要导出的数据
        list = teacherImp.selectList(queryWrapper);

        System.out.println(list);

        //设置文件名
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
        String fileName = simpleDateFormat.format(new Date())+"_TeacherList.xls";
        if (isTemplate){
            fileName = simpleDateFormat.format(new Date())+"_TeacherTemplate.xls";
        }

        //小标题
        String[] title = {"工号","姓名","性别","出生日期","入职日期","身份"};
        //列宽
        int[] columnWidth = {15,15,15,25,25,15};
        //导出
        excelUtil.exportToExcel(fileName,title,columnWidth,list,response,"teacher",isTemplate);
    }

    @GetMapping("/selectAll")
    public Result<List<Teacher>> selectAll(){

        List<Teacher> teacherList = teacherImp.selectList(new QueryWrapper<>());

        return Result.success(teacherList);
    }

    @PostMapping("/importData")
    public Result<List<Teacher>> importData(@RequestBody List<Map<String,String>> teacherList) throws ParseException {
        ArrayList<Teacher> insertList = new ArrayList<>();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        System.out.println(teacherList);
        for (Map<String, String> map : teacherList) {
            Teacher teacher = new Teacher();
            if (!"".equals(map.get("id"))){//有工号 判断是否存在该老师，存在则不插入，否则插入
                if (teacherImp.selectOne(Integer.parseInt(map.get("id"))) == null) {
                    teacher.setId(Integer.parseInt(map.get("id")));
                    teacher.setName(map.get("name"));
                    teacher.setSex(map.get("sex"));
                    teacher.setBirthday(sdf.parse(map.get("birthday")));
                    teacher.setPassword(MD5Util.md5(OriginPsw.getOriginPassword()));
                    teacher.setJoinDate(sdf.parse(map.get("joinDate")));
                    teacherImp.insert(teacher);
                    insertList.add(teacher);
                }
            }else {//无工号 全部插入
                teacher.setName(map.get("name"));
                teacher.setSex(map.get("sex"));
                teacher.setBirthday(sdf.parse(map.get("birthday")));
                teacher.setPassword(MD5Util.md5(OriginPsw.getOriginPassword()));
                teacher.setJoinDate(sdf.parse(map.get("joinDate")));
                teacherImp.insert(teacher);
                insertList.add(teacher);
            }
        }

        return Result.success(insertList);
    }

    @PostMapping("/batchResetPsw")
    public Result<Student> batchResetPsw(@RequestBody Map<String,String> map){
        String ids = map.get("ids");
        boolean flag = true;
        String[] id = ids.split(",");
        for (String s : id) {
            Teacher teacher = teacherImp.selectOne(Integer.parseInt(s));
            teacher.setPassword(MD5Util.md5(OriginPsw.getOriginPassword()));
            if (teacherImp.updateById(teacher)==0)
                flag = false;
        }

        if (flag)
            return Result.success("成功！初始化密码为"+OriginPsw.getOriginPassword());
        return Result.fail();
    }

}
